package com.dji.sample.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dji.sample.common.model.Pagination;
import com.dji.sample.common.model.PaginationData;
import com.dji.sample.manage.dao.LiveInfoMapper;
import com.dji.sample.manage.model.dto.LiveInfoDTO;
import com.dji.sample.manage.model.entity.DevicePlayLineEntity;
import com.dji.sample.manage.model.entity.LiveInfoEntity;
import com.dji.sample.manage.service.LiveInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author yjt
 * @date 2023-02-07
 * @description:
 */
@Service
public class LiveInfoServiceImpl implements LiveInfoService {

    @Autowired
    LiveInfoMapper liveInfoMapper;

    @Value("${video.domain}")
    private String videoDomain;

    @Value("${video.savepwd}")
    private String videoSavePwd;

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public PaginationData<LiveInfoDTO> findByRoomId(String roomId, Integer page, Integer pageSize, String startTime, String endTime) {
        Page<LiveInfoEntity> result = liveInfoMapper.selectPage(new Page<>(page, pageSize), new LambdaQueryWrapper<LiveInfoEntity>().select(LiveInfoEntity::getId, LiveInfoEntity::getFilePath, LiveInfoEntity::getCreateTime, LiveInfoEntity::getEndTime, LiveInfoEntity::getRoomId, LiveInfoEntity::getStream).isNotNull(LiveInfoEntity::getFilePath).eq(LiveInfoEntity::getRoomId, roomId)
                .ge(StringUtils.hasText(startTime), LiveInfoEntity::getCreateTime, startTime).le(StringUtils.hasText(endTime), LiveInfoEntity::getCreateTime, endTime).orderByDesc(LiveInfoEntity::getId));

        Page<LiveInfoDTO> page1 = new Page<>();
        BeanUtils.copyProperties(result, page1);
        List<LiveInfoDTO> list = new ArrayList<>();
        String uuid = UUID.randomUUID().toString();
        if (Boolean.TRUE.equals(redisTemplate.hasKey("video:sign:" + roomId))) {
            uuid = Objects.requireNonNull(redisTemplate.opsForValue().get("video:sign:" + roomId)).toString();
            redisTemplate.expire("video:sign:" + roomId, 1, TimeUnit.HOURS);
            redisTemplate.expire("video:sign:" + uuid, 1, TimeUnit.HOURS);
        } else {
            redisTemplate.opsForValue().set("video:sign:" + roomId, uuid, 1, TimeUnit.HOURS);
            redisTemplate.opsForValue().set("video:sign:" + uuid, "1", 1, TimeUnit.HOURS);
        }
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"));
        String param = "?sign=" + uuid + "&time=" + time + "&expire=3600";
        for (LiveInfoEntity record : result.getRecords()) {
            list.add(new LiveInfoDTO(record.getRoomId(), record.getCreateTime(), record.getEndTime(), record.getFilePath().replace(videoSavePwd, videoDomain) + param, record.getId()));
        }
        page1.setRecords(list);
        return new PaginationData<>(page1.getRecords(), new Pagination(page1));
    }

    @Override
    public void deleteVideo(Long id) {
        LiveInfoEntity liveInfo = new LiveInfoEntity();
        liveInfo.setId(id);
        liveInfo.setStatus(2);
        liveInfoMapper.updateById(liveInfo);
        //广播消息 broker删除视频
        redisTemplate.convertAndSend("rm:video", id);
    }
}
